package org.visionlibrary.image.filters.adjustement;

import javax.media.jai.TiledImage;

import org.visionlibrary.image.acquisition.ImageFactory;
import org.visionlibrary.image.model.AbstractFilter;


public class C16bitTo8bit extends AbstractFilter {
	@Override
	public TiledImage applyFilter(TiledImage src, TiledImage dest) {
		if(null == src)
			throw new NullPointerException("Source image is null.");
		
		if(null != dest)
			throw new IllegalArgumentException("Destination image argument should be null!");
		
		dest = (new ImageFactory()).createCompatible8BitImage(src);
		
		int maxX = src.getWidth();
		int maxY = src.getHeight();
		int bands = src.getNumBands();
		
		for(int x=0; x < maxX; x++)
			for(int y=0; y < maxY; y++)
				for(int b=0; b < bands; b++) {
					int pixel = src.getSample(x, y, b);
					pixel = (int)((pixel/65535.0d) * 255);
					if(pixel > 255)
						pixel = 255;
						
					dest.setSample(x, y, b, pixel);
				}
		
		return dest;
	}
}
